<?php
namespace app\lib;
use think\Db;
use think\Cache;
use think\Config;

class WxApp {
    const CACHE_KEY = 'WxConfig_';
    public $wx = null; //微信类
    public $template = null; //模板类
    public $config = null;
    public static $ty_id = 0; //社区ID
    /*
     * $template 是否new模版类*/
    public function __construct($ty_id=0,$template=false) {
        self::$ty_id = $ty_id;
        $this->getWxConfig();
        vendor('weixin.code');
        $this->wx = new \code($this->config['appid'],$this->config['appsecret']);
        if( $template ) {
            vendor('weixin.template');
            $this->template = new \template();
        }
    }

    public function getWxConfig(){
        if( self::hasCache() ) {
            $this->config = self::getCache();
        } else {
            $this->config = Db::name('weixin')->where('ty_id='.self::$ty_id)->field('appid,mchid,key,appsecret,access_token,expires_time')->find();
            self::setCache($this->config);
        }
    }
    /*
         * $wxConfig*/
    public function getTokenCache(){
        //还没创建过
        if( time() - $this->config['expires_time'] > 7000 ) {
            $token = $this->wx->getToken($this->config['appid'],$this->config['appsecret']);
            Db::name('weixin')->where(['ty_id'=>$this->ty_id])->update(['access_token'=>$token,'expires_time'=>time()]);
            $this->config = array_merge($this->config,['access_token'=>$token,'expires_time'=>time()]);
            return $token;
        } else {
            return $this->config['access_token'];
        }
    }

    public static function setCache($arr) {
        Cache::set(Config::get('cache_fix') . self::CACHE_KEY.self::$ty_id, $arr, 7000);
    }

    public static function getCache() {
        return Cache::get(Config::get('cache_fix') . self::CACHE_KEY.self::$ty_id);
    }

    public static function hasCache() {
        return Cache::has(Config::get('cache_fix') . self::CACHE_KEY.self::$ty_id);
    }
    public static function rmCache() {
        return Cache::rm(Config::get('cache_fix') . self::CACHE_KEY.self::$ty_id);
    }
}
